<?php

class GBook {
	
	private $searchUrl = '';
	private $loginUrl = '';
	private $u = '';
	private $p = '';
	private $refer = '';
	private $cookie_file = '';
	
	private $fileDir = '';
	private $afterDir = '';
	private $newDir = '';
	private $oldDir = '';
	private $infoDir = '';
	
	function __construct(){
		$this->searchUrl = "http://www.78xs.com/Book/Search.aspx";
		$this->loginUrl = "http://www.78xs.com/User/LoginCheck.aspx";
		$this->refer = "http://www.78xs.com/user/login.aspx";
		$this->u = "shuqi";
		$this->p = "shuqibook";
		
		$this->filedir = dirname(__FILE__);
		$this->afterDir = $this->filedir.'/after/';
		$this->newDir = $this->filedir.'/new/';
		$this->oldDir = $this->filedir.'/old/';
		$this->infoDir = $this->filedir.'/info/';
		
		$this->cookie_file = dirname(__FILE__).'/cookie.txt';
	}
	
	/**
	 * 登录
	 */
	public function login(){
		$header = array(
			"User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.31 (KHTML, like Gecko) Chrome/26.0.1410.64 Safari/537.31",
			"Content-Type: application/x-www-form-urlencoded",
			"Referer: http://www.78xs.com/user/login.aspx",
		);
		
		$post_data = array(
			'username' => $this->u,
			'password' => $this->p,
			'CookieTime' => 30,
			'UserLogin'=> '%B5%C7%C2%BC'
		);
		
		$ch = curl_init();
		curl_setopt($ch, CURLOPT_URL, $this->loginUrl);
		curl_setopt($ch, CURLOPT_TIMEOUT, 30);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_HTTPHEADER, array("Referer: {$this->refer}"));
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
		curl_setopt($ch, CURLOPT_POST, 1);
		curl_setopt($ch, CURLOPT_POSTFIELDS, $post_data);
		curl_setopt($ch, CURLOPT_COOKIEJAR, $this->cookie_file);
		$result = curl_exec($ch);
		curl_close($ch);
		
		$r = mb_convert_encoding($result, 'utf8', 'gb2312');
		preg_match('/href=\'(?P<uuuu>.{1,})\'/u', $r, $match);
		
		print_r($match['uuuu']);
	}
	
	/**
	 * 搜索
	 * 
	 * @param String $searchKey
	 * @return boolean
	 */
	public function search($searchKey, $echo=false){
		if(!$searchKey)return false;
		
		$searchclass = 1;	// 0 按作者  1 按书名 2 按主角
		
		$ch = curl_init($this->searchUrl."?SearchKey=".urlencode($searchKey)."&SearchClass={$searchclass}");
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_COOKIEFILE, $this->cookie_file); //使用上面获取的cookies
		$response = curl_exec($ch);
		curl_close($ch);
		
		$response = mb_convert_encoding($response, 'utf8', 'gb2312');
				
		preg_match_all("/Book\/\d{2,}.aspx/", $response, $matches);
		preg_match_all("/ShowBookList.aspx\?tclassid=(?P<cateId>\d{1,})\">(?P<cateName>.*?)<\/a>/", $response, $cates);
		preg_match_all("/最新章节 >>> <a href=\".*?\" target=\"_blank\">(?P<lastC>.*?)<\/a>/", $response, $lastCharpter);
		
		$downloadList = array();
		foreach ($matches as $k => $v){
			$v = str_ireplace('Book/', '', $v);
			$v = str_ireplace('.aspx', '', $v);
			foreach ($v as $i){
				if($i=='483')continue;	// 过滤默认书本
				if(in_array($i, $downloadList))continue;  //如果包含本书跳过
				$downloadList[] = $i;
			}
		}
		
		if($echo){
 			print_r($cates); echo "\n";
 			print_r($lastCharpter); echo "\n";
 			print_r($downloadList); echo "\n";
		}
		
		if(empty($downloadList)){
			return false;
		}
		
		foreach ($downloadList as $key => $b){
			$bookInfo = array();
			$bookInfo['cateId'] = $cates['cateId'][$key];
			$bookInfo['cateName'] = $cates['cateName'][$key];
			$bookInfo['last'] = $lastCharpter['lastC'][$key];
			$this->writeBookInfo($b, $bookInfo);	//写入部分书本信息
			
			$this->download_rar($b, $this->cookie_file);	
		}
		return true;
	}
	
	public function spiltBook(){
		
		$newdir = $this->newDir;
		$olddir = $this->oldDir;
		$afterdir = $this->afterDir;
		
		// 把下载的书籍解压， 并生成单独文件（转码）
		if (is_dir($olddir)) {
			if ($dh = opendir($olddir)) {
				while (($file = readdir($dh)) !== false) {
					if ($file!="." && $file!=".." && $file!=".svn") {
						$size = filesize($olddir.$file);
						if($size==false || $size<10)continue;
						$rar_file = rar_open($olddir.$file) or die("Failed to open Rar archive");
						$entries_list = rar_list($rar_file);
						foreach ($entries_list as $entry) {
							$n = $entry->getName();
							echo 'Filename: ' . $n . "<br />";
							$stream = $entry->getStream();
		
							if(file_exists($newdir.$n)){	// 如果文件存在， 删除
								unlink($newdir.$n);
							}
		
							while (!feof($stream)) {
								$buff = fread($stream, 8192);
								if ($buff !== false){
									$buff = mb_convert_encoding($buff, 'utf8', 'EUC-CN'). "<br />";
									file_put_contents($newdir.$n, $buff, FILE_APPEND);
								}else
									break; //fread error
							}
		
							fclose($stream);
							echo 'Done: ' . $n . "<br />";
						}
						rar_close($rar_file);
					}
				}
				closedir($dh);
			}
		}
		
		// 打散文件， 并生成新zip文件
		if (is_dir($newdir)) {
			if ($dh = opendir($newdir)) {
				while (($file = readdir($dh)) !== false) {
					if ($file!="." && $file!=".." && $file!=".svn") {
						$l = explode('.', $file);
						$localdir = $l[0].'/';	// article dir
		
						if(!is_dir($afterdir.$localdir)){
							mkdir($afterdir.$localdir, 0777, true);
						}
		
						$s = file_get_contents($newdir.$file);
		
						$list = explode("------章节内容开始-------\r\n", $s);
		
						$b = explode("]", $list[0]);
						$b[0] = str_ireplace('[', '', $b[0]);
						$b[0] = str_ireplace(' ', '', $b[0]);
						$b[0] = str_ireplace('著', '', $b[0]);
		
						$bookInfo = array();
						$article = explode("/", $b[0]);
						$bookInfo['title'] = $article[0];	// title
						$bookInfo['author'] = $article[1];	// author
		
						$desc = explode("书籍介绍:", $b[1]);
						$bookInfo['desc'] = $article[1];	// desc
		
						$bookid = str_ireplace('/', '', $localdir);
						$this->writeBookInfoAddEnd($bookid, $bookInfo);	// 把另外部分信息写入文件
		
						$a = explode("\r\n\r\n\r\n\r\n", $list[1]);
	
						unset($b);
						unset($article);
						unset($list);
						$i = 0;
						foreach ($a as $k => $v){
							if(empty($v))continue;
							if(stripos($v, "Copyright (C) 2000-2007 http://www.78xs.com　　All Rights Reserved　　
    本书已获作者授权在78小说网(http://www.78xs.com)及78小说网合作伙伴处进行网络连载，未经作者或78小说网许可者请勿转载。
　　作品本身仅代表作者本人的观点，与78小说网立场无关。阅读者如发现作品内容确有与法律抵触之处，可向78小说网举报。　　如因而由此导致任何法律问题或后果，78小说网均不负任何责任。<br />    [天骄无双 / 跳舞 著 ]
    78小说网 出品作品Txt版阅读,阅读作品更多请访问:http://www.78xs.com")!==false)continue;
								
							$t = explode("78小说网", $v);
							$charpter = trim($t[0]);	//Charpter
							$charpter = str_ireplace("Copyright (C) 2000-2007 http://www.78xs.comx", '', $charpter);
							$charpter = str_ireplace("Copyright (C) 2000-2007 http://www.78xs.com", '', $charpter);
							$charpter = str_ireplace("All Rights Reserved", '', $charpter);
							$charpter = str_ireplace("本书已获作者授权在", '', $charpter);
							$charpter = str_ireplace("\r\n", '', $charpter);
								
							$charpter = trim($charpter);
							file_put_contents($afterdir.$localdir.'charpter.txt', $charpter."\n", FILE_APPEND);	// write charpter txt
						
							$v = $this->v($v);	// 过滤
							file_put_contents($afterdir.$localdir.$i.'.txt', $v);

							unset($t);
							unset($charpter);
							echo $k.'|Done!<br />';
							$i++;
						}
						unset($s);
		
						$this->v_zip($afterdir.$localdir, $afterdir.$l[0].'.zip');
						
						$zip_path = $afterdir.$l[0].'.zip';
						// 上传OSS
						$rs = G::get_oss()->uploadByFile(basename($zip_path), $zip_path);
						echo $rs['url'];
					}
				}
			}
		}
		
		// 删除中间文件
		$this->deleteFileOfDir($this->oldDir);
		$this->deleteFileOfDir($this->newDir);
		$this->deleteFileOfDir($this->afterDir);
	}
	
	
	/***************************************************************************************/
	
	// 下载rar
	private function download_rar($id, $cookie_file){
		$download = "http://www.78xs.com/Book/[placehoder]/Txt.aspx";
		
		$url = str_ireplace('[placehoder]', $id, $download);
		
		$local_file = $this->oldDir.$id.".rar";
		
		echo '<br />Download url:'.$url;
		
		// 第一次拿链接
		$rfp = curl_init($url);
		curl_setopt($rfp, CURLOPT_HEADER, 0);
		curl_setopt($rfp, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($rfp, CURLOPT_COOKIEFILE, $cookie_file); //使用上面获取的cookies
		$response = curl_exec($rfp);
		curl_close($rfp);
		// 第一次拿链接结束
		
		preg_match_all("/http:\/\/.+.rar/", $response, $matches);
		
		//过滤地址再次下载
		$ch = curl_init($matches[0][0]);
		curl_setopt($ch, CURLOPT_HEADER, 0);
		curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
		curl_setopt($ch, CURLOPT_COOKIEFILE, $cookie_file); //使用上面获取的cookies
		
		$s = curl_exec($ch);
		curl_close($ch);
		
		file_put_contents($local_file, $s);
		
		echo '<br />'.$id.':Download Done!';
	}
	
	// 过滤
	private function v($str){
		
		$str = preg_replace("/\/\/.+?\/\//",'',$str);
		$str = preg_replace("/\[.+?]/",'',$str);
		$str = preg_replace("/(.百度+?)/",'',$str);
		$str = str_ireplace('百度搜索：78小说网看小说', '', $str);
		$str = str_ireplace('http://www.78xs.com', '', $str);
		$str = str_ireplace('www.78xs.com', '', $str);
		$str = str_ireplace('(7~8小说网全文字小说更新最快)', '', $str);
		$str = str_ireplace('欢迎来到7~8小说网阅读七八xs网址简单好记', '', $str);
		$str = str_ireplace('(本章节由7~8小说网友上传)', '', $str);
		$str = str_ireplace('78小说网', '', $str);
		$str = str_ireplace('7~8小说网', '', $str);
		$str = str_ireplace('搜索：', '', $str);
		$str = str_ireplace('看小说', '', $str);
		$str = str_ireplace('()', '', $str);
			
		return $str;
	}
	
	// zip 压缩文件
	private function v_zip($path, $zipname){
		$zip = new ZipArchive;
	
		if ($zip->open($zipname, ZipArchive::OVERWRITE) === TRUE){
			$handler = opendir($path);
			while( ($filename = readdir($handler)) !== false ){
				if($filename != "." && $filename != ".." && $filename!=".svn"){
					if(is_file($path."/".$filename)){
						$zip->addFile($path."/".$filename, basename($filename));
					}
				}
			}
			closedir($handler);
			$zip->close();
		}
	}
	
	// 批量删除文件夹下文件
	public function deleteFileOfDir($dir){
		//先删除目录下的文件：
		if (is_dir($dir)) {
			$dh=opendir($dir);
			while ($file=readdir($dh)) {
				if($file!="." && $file!=".." && $file!=".svn") {
					$fullpath=$dir.$file;
					if(!is_dir($fullpath)) {
						unlink($fullpath);
					} else {
						$this->deleteFileOfDir($fullpath.'/');
					}
				}
			}
			closedir($dh);
		}
		
		//删除当前文件夹：
		if($dir!=$this->afterDir && $dir!=$this->newDir && $dir!=$this->oldDir && $dir!=$this->infoDir) {
			rmdir($dir);
		}
	}
	
	
	private function writeBookInfo($id, $array){
		$s = json_encode($array);
		file_put_contents($this->infoDir.$id.'.txt', $s);
	}
	
	private function writeBookInfoAddEnd($id, $array){
		$s = file_get_contents($this->infoDir.$id.'.txt');
		$s = json_decode($s, true);
		$m = array_merge($s, $array);
		$m = json_encode($m);
		file_put_contents($this->infoDir.$id.'.txt', $m);
	}
}
